package com.learn.thread;

import java.sql.Array;
import java.util.ArrayList;

/**
 * 线程通信(生产者，消费者问题)
 * 产品，生产者，消费者，缓存
 */
public class Test25110701 {
    public static void main(String[] args) {
        ProductCache003 productCache = new ProductCache003();
        new Thread(new Producer003(productCache)).start();
        new Thread(new Consumer003(productCache)).start();
    }
}

class Product003 {
    private int id;

    public Product003(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

class Producer003 implements Runnable {

    //生产商品
    private ProductCache003 productCache;

    public Producer003(ProductCache003 productCache) {
        this.productCache = productCache;
    }

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            System.out.println("生产者生产第几个产品--->" + i);
            productCache.produce(new Product003(i));
        }
    }
}

class Consumer003 implements Runnable {

    //消费商品
    private ProductCache003 productCache;

    public Consumer003(ProductCache003 productCache) {
        this.productCache = productCache;
    }

    @Override
    public void run() {

        while (true) {
            System.out.println("消费者开始消费第几个产品--->" + productCache.cousume().getId());
            if (productCache.cousume().getId() == 100) {
                return;
            }
        }
    }

}

class ProductCache003 {
    //商品缓存
    private Product003[] productsArr = new Product003[10];
    private int count = 0;

    //
    public synchronized void produce(Product003 product) {
        //超过10个等待
        if (productsArr.length == count) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //生产商品添加到缓存中
        productsArr[count] = product;
        //自增
        count++;

        notifyAll();
    }

    public synchronized Product003 cousume() {
        //count为0 需要等待
        if (count == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //自减
        count--;
        Product003 product = productsArr[count];
        notifyAll();
        return product;
    }


}